 //shredder.c

//includes
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>

//globals
 



//main
int main(int argc,char* argv[],char* envp[]){ 

 //for reading input
char readBuffer[1025];
char wasteBuffer[1025]; 
int charsRead; 

 //our output strings 
const char prompt[]="shredder# "; 
const char successMsg[]="Arggg ... Bee-Bop, how could you let them get away?!?\n"; 
const char readError[]="There was an error reading your input, please try again";  

int status;   //child's status 


//the real action begins
while (1){ 
   if(write(1,prompt,10)==-1){ 
     //write error 
     perror(writeError); 
     _exit(2);
   } 

   //read user input 
   charsRead=read(0,readBuffer,1025); 
   if(charsRead==-1){
	//read error 
     write(1,readError,56); 
     continue; //gonna try again, maybe should exit?
   }
  
   //if our input exceeds 1024 chars, lets flush it all out by reading it
   if(charsRead>1024){
     while(read(0,wasteBuffer,1025)>1024);
   }
    
  //read seems to read one too many chars (eof char?) 
   readBuffer[charsRead-1]='\0'; 
   charsRead--; 

   //create child   
   pid=fork(); 
  
   //if we're child process 
   if(!pid){ 

     //call our custom exec function
     //will parse and execute input
     child_exec(readBuffer);
   } 
   //adult process 
   else{ 
     if(wait(&status)==-1){
	//wait error
 
	//this seemed to be the problem with compiling with c99: 
      //if wait is interrupted by a signal, it returns error and doesnt change status properly
      //we restart wait, to get the proper status and functionality
      //otherwise, next iteration, wait will still give this iteration's status
     // wait(&status);
    }
    //clear alarm; it to be cleared either way
    //if it went over time, alarm already went off, otherwise program made it in time 
     alarm(0);
     
     //if alarm exited normally (not by singal) AND with a clean status (0)
     if (WIFEXITED(status) && WEXITSTATUS(status)==0)
       if(write(1,successMsg,54)==-1){
	//write error
	 perror(writeError);
	 _exit(2);

       }

       }
 }

}

